"use client"

import { useState, useEffect } from "react"
import { AuthGuard } from "@/components/auth-guard"
import { DashboardLayout } from "@/components/dashboard-layout"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/hooks/use-toast"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Plus, Edit, Trash2, Save, Key, Globe, Cpu, AlertCircle } from "lucide-react"
import type { ModelProvider } from "@/app/api/model-providers/route"

// 预定义的模型供应商
const PREDEFINED_PROVIDERS = [
  { id: "OPENAI", name: "OpenAI", defaultBaseUrl: "https://api.openai.com/v1" },
  { id: "ANTHROPIC", name: "Anthropic Claude", defaultBaseUrl: "https://api.anthropic.com" },
  { id: "GOOGLE", name: "Google Gemini", defaultBaseUrl: "https://generativelanguage.googleapis.com" },
  { id: "AZURE", name: "Azure OpenAI", defaultBaseUrl: "" },
  { id: "QWEN", name: "阿里通义千问", defaultBaseUrl: "https://dashscope.aliyuncs.com/api/v1" },
  { id: "GLM", name: "智谱 ChatGLM", defaultBaseUrl: "https://open.bigmodel.cn/api/paas/v4" },
  { id: "ERNIE", name: "百度文心一言", defaultBaseUrl: "https://aip.baidubce.com" },
  { id: "DEEPSEEK", name: "DeepSeek", defaultBaseUrl: "https://api.deepseek.com" },
  { id: "MOONSHOT", name: "月之暗面 Kimi", defaultBaseUrl: "https://api.moonshot.cn/v1" },
]

export default function ModelSettingsPage() {
  const { toast } = useToast()
  const [providers, setProviders] = useState<ModelProvider[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingProvider, setEditingProvider] = useState<ModelProvider | null>(null)

  // 表单状态
  const [formData, setFormData] = useState({
    id: "",
    name: "",
    apiKey: "",
    baseUrl: "",
    enabled: true,
  })

  // 加载配置
  useEffect(() => {
    loadProviders()
  }, [])

  const loadProviders = async () => {
    try {
      setLoading(true)
      const response = await fetch("/api/model-providers")
      const result = await response.json()

      if (result.success) {
        setProviders(result.data || [])
      } else {
        toast({
          title: "加载失败",
          description: result.error || "无法加载模型配置",
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error("Error loading providers:", error)
      toast({
        title: "加载失败",
        description: "网络错误，请稍后重试",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    try {
      setSaving(true)

      const response = await fetch("/api/model-providers", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ providers }),
      })

      const result = await response.json()

      if (result.success) {
        toast({
          title: "保存成功",
          description: "模型配置已写入 .env 文件",
        })
      } else {
        toast({
          title: "保存失败",
          description: result.error || "无法保存配置",
          variant: "destructive",
        })
      }
    } catch (error) {
      console.error("Error saving providers:", error)
      toast({
        title: "保存失败",
        description: "网络错误，请稍后重试",
        variant: "destructive",
      })
    } finally {
      setSaving(false)
    }
  }

  const openAddDialog = () => {
    setEditingProvider(null)
    setFormData({
      id: "",
      name: "",
      apiKey: "",
      baseUrl: "",
      enabled: true,
    })
    setDialogOpen(true)
  }

  const openEditDialog = (provider: ModelProvider) => {
    setEditingProvider(provider)
    setFormData({
      id: provider.id,
      name: provider.name,
      apiKey: "", // 不显示现有的 API Key，需要用户重新输入
      baseUrl: provider.baseUrl,
      enabled: provider.enabled,
    })
    setDialogOpen(true)
  }

  const handleDialogSave = () => {
    if (!formData.id || !formData.name || (!editingProvider && !formData.apiKey)) {
      toast({
        title: "验证失败",
        description: "请填写所有必填项",
        variant: "destructive",
      })
      return
    }

    if (editingProvider) {
      // 编辑现有配置
      setProviders((prev) =>
        prev.map((p) =>
          p.id === editingProvider.id
            ? {
                ...p,
                name: formData.name,
                apiKey: formData.apiKey || p.apiKey, // 如果没有输入新的，保留旧的
                baseUrl: formData.baseUrl,
                enabled: formData.enabled,
              }
            : p,
        ),
      )
      toast({
        title: "已更新",
        description: `${formData.name} 配置已更新，请点击 "保存到 .env"`,
      })
    } else {
      // 添加新配置
      if (providers.some((p) => p.id === formData.id)) {
        toast({
          title: "ID 冲突",
          description: "该供应商 ID 已存在",
          variant: "destructive",
        })
        return
      }

      setProviders((prev) => [
        ...prev,
        {
          id: formData.id,
          name: formData.name,
          apiKey: formData.apiKey,
          baseUrl: formData.baseUrl,
          enabled: formData.enabled,
        },
      ])
      toast({
        title: "已添加",
        description: `${formData.name} 已添加，请点击 "保存到 .env"`,
      })
    }

    setDialogOpen(false)
  }

  const handleDelete = (id: string) => {
    setProviders((prev) => prev.filter((p) => p.id !== id))
    toast({
      title: "已删除",
      description: '供应商已删除，请点击 "保存到 .env" 以确认更改',
    })
  }

  const toggleEnabled = (id: string) => {
    setProviders((prev) =>
      prev.map((p) => (p.id === id ? { ...p, enabled: !p.enabled } : p)),
    )
  }

  const handleProviderSelect = (providerId: string) => {
    const predefined = PREDEFINED_PROVIDERS.find((p) => p.id === providerId)
    if (predefined) {
      setFormData({
        ...formData,
        id: predefined.id,
        name: predefined.name,
        baseUrl: predefined.defaultBaseUrl,
      })
    }
  }

  return (
    <AuthGuard>
      <DashboardLayout>
        <div className="space-y-6">
          {/* 页面标题 */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
                <Cpu className="h-8 w-8" />
                模型管理
              </h1>
              <p className="text-muted-foreground mt-2">
                配置大语言模型供应商的 API 密钥和基础 URL
              </p>
            </div>
            <div className="flex items-center gap-2">
              <Button onClick={openAddDialog} size="sm">
                <Plus className="mr-2 h-4 w-4" />
                添加供应商
              </Button>
              <Button onClick={handleSave} disabled={saving} variant="default">
                <Save className="mr-2 h-4 w-4" />
                {saving ? "保存中..." : "保存到 .env"}
              </Button>
            </div>
          </div>

          {/* 提示信息 */}
          <Card className="bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
            <CardContent className="pt-6">
              <div className="flex gap-3">
                <AlertCircle className="h-5 w-5 text-blue-600 dark:text-blue-400 shrink-0 mt-0.5" />
                <div className="space-y-1 text-sm">
                  <p className="font-medium text-blue-900 dark:text-blue-100">
                    配置说明
                  </p>
                  <ul className="text-blue-800 dark:text-blue-200 space-y-1 list-disc list-inside">
                    <li>添加或编辑供应商配置后，需点击 "保存到 .env" 按钮才会写入配置文件</li>
                    <li>配置将保存在项目根目录的 .env 文件中</li>
                    <li>修改配置后需要重启开发服务器才能生效</li>
                    <li>API Key 会被部分隐藏以保护安全</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 供应商列表 */}
          <Card>
            <CardHeader>
              <CardTitle>已配置的供应商</CardTitle>
              <CardDescription>
                管理所有已配置的模型供应商，启用的供应商将在 Agent 管理中可用
              </CardDescription>
            </CardHeader>
            <CardContent>
              {loading ? (
                <div className="flex items-center justify-center py-8">
                  <div className="h-8 w-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
                </div>
              ) : providers.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Cpu className="h-12 w-12 mx-auto mb-3 opacity-50" />
                  <p>暂无配置的供应商</p>
                  <p className="text-sm mt-1">点击"添加供应商"开始配置</p>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>供应商</TableHead>
                      <TableHead>API Key</TableHead>
                      <TableHead>Base URL</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {providers.map((provider) => (
                      <TableRow key={provider.id}>
                        <TableCell className="font-medium">
                          <div className="flex items-center gap-2">
                            <Cpu className="h-4 w-4" />
                            {provider.name}
                            <Badge variant="outline" className="text-xs">
                              {provider.id}
                            </Badge>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2 text-xs font-mono">
                            <Key className="h-3 w-3" />
                            {provider.apiKey}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2 text-xs">
                            <Globe className="h-3 w-3" />
                            {provider.baseUrl || <span className="text-muted-foreground">未设置</span>}
                          </div>
                        </TableCell>
                        <TableCell>
                          <Switch
                            checked={provider.enabled}
                            onCheckedChange={() => toggleEnabled(provider.id)}
                          />
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex items-center justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openEditDialog(provider)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(provider.id)}
                              className="text-destructive hover:text-destructive"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </div>

        {/* 添加/编辑对话框 */}
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              <DialogTitle>{editingProvider ? "编辑供应商" : "添加供应商"}</DialogTitle>
              <DialogDescription>
                {editingProvider
                  ? "修改供应商配置信息"
                  : "添加新的模型供应商配置"}
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4">
              {!editingProvider && (
                <div className="space-y-2">
                  <Label>选择供应商模板</Label>
                  <Select onValueChange={handleProviderSelect}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择预定义的供应商或手动输入" />
                    </SelectTrigger>
                    <SelectContent>
                      {PREDEFINED_PROVIDERS.map((p) => (
                        <SelectItem key={p.id} value={p.id}>
                          {p.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="id">
                    供应商 ID <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="id"
                    value={formData.id}
                    onChange={(e) => setFormData({ ...formData, id: e.target.value.toUpperCase() })}
                    placeholder="OPENAI"
                    disabled={!!editingProvider}
                  />
                  <p className="text-xs text-muted-foreground">
                    大写字母和下划线，如：OPENAI
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="name">
                    显示名称 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="OpenAI"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="apiKey">
                  API Key {!editingProvider && <span className="text-destructive">*</span>}
                </Label>
                <Input
                  id="apiKey"
                  type="password"
                  value={formData.apiKey}
                  onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
                  placeholder={editingProvider ? "留空表示不修改" : "sk-..."}
                />
                {editingProvider && (
                  <p className="text-xs text-muted-foreground">
                    留空则保留原有的 API Key
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="baseUrl">Base URL</Label>
                <Input
                  id="baseUrl"
                  value={formData.baseUrl}
                  onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
                  placeholder="https://api.openai.com/v1"
                />
                <p className="text-xs text-muted-foreground">
                  API 基础地址，某些供应商可不填
                </p>
              </div>

              <div className="flex items-center space-x-2">
                <Switch
                  id="enabled"
                  checked={formData.enabled}
                  onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
                />
                <Label htmlFor="enabled">启用此供应商</Label>
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={() => setDialogOpen(false)}>
                取消
              </Button>
              <Button onClick={handleDialogSave}>
                {editingProvider ? "更新" : "添加"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </DashboardLayout>
    </AuthGuard>
  )
}
